package com.roy.netty.pojoTransfer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/8
 * @description: 将字节流翻译成为POJO
 **/

public class PojoDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        //按定长读取字节流
        System.out.println("读到的字符长度："+in.readableBytes());
        final int userId = in.readInt();
        final double userSalary = in.readDouble();
        //字符串长度不固定
//        int userNameLen = in.readableBytes();
//        System.out.println("剩余的用户名字符串长度："+userNameLen);
//        final ByteBuf userNameBuffer = in.readBytes(userNameLen);
//        final String userName = userNameBuffer.toString(Charset.forName("utf-8"));
        //处理粘包问题的一种方法，按固定长度读取username的字节流
        final int usernameLength = in.readInt();
        final ByteBuf userNameBuffer = in.readBytes(usernameLength);
        final String userName = userNameBuffer.toString(Charset.forName("utf-8"));

        User user = new User();
        user.setUserId(userId);
        user.setUserSalary(userSalary);
        user.setUserName(userName);

        out.add(user);
    }
}
